﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Fluq;

namespace Fluq
{
	public sealed class AutoDependencyRegistry : IDependencyRegistry
	{
		private IDependencyRegistry _registry;

		public AutoDependencyRegistry(IDependencyRegistry registry)
		{
			if (registry == null)
			{
				throw new ArgumentNullException("registry");
			}

			_registry = registry;
		}

		public void Add(IEnumerable<IDependency> dependencies)
		{
			_registry.Add(dependencies);
		}

		public IEnumerable<IDependency> Find(IDependencyKey key)
		{
			IEnumerable<IDependency> found = _registry.Find(key);

			if (!found.Any() && IsCandidiateType(key.Type))
			{
				Func<IDependencyContainer, IEnumerable<IDependencyParameter>, object> factory = (c, p) =>
				{
					object instance;

					c.Composer.TryCompose(c, key.Type, p, out instance);

					return instance;
				};

				found = new IDependency[] { new AutoDependency(key, factory) };

				Add(found);
			}

			return found;
		}

		private static bool IsCandidiateType(Type type)
		{
			return type.IsClass && !type.IsSubclassOf(typeof(Delegate));
		}
	}
}
